package com.woniuxy.orderserver.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.common.dto.SkuDto;
import com.woniuxy.common.dto.UserDto;
import com.woniuxy.common.utils.SnowflakeIdGenerator;
import com.woniuxy.common.utils.UserUtil;
import com.woniuxy.orderserver.pojo.FinanceOrderDetail;
import com.woniuxy.orderserver.service.FinanceOrderDetailService;
import com.woniuxy.orderserver.mapper.FinanceOrderDetailMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
* @author 76169
* @description 针对表【finance_order_detail】的数据库操作Service实现
* @createDate 2024-12-17 19:03:25
*/
@Slf4j
@Service
public class FinanceOrderDetailServiceImpl extends ServiceImpl<FinanceOrderDetailMapper, FinanceOrderDetail>
    implements FinanceOrderDetailService{
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private HttpServletRequest request;


    @Autowired
    private ObjectMapper objectMapper; // 注入 ObjectMapper
    @Override
    public List<FinanceOrderDetail> addOrderDetail() throws InterruptedException{
        //1.获取用户信息
        UserDto userDto = UserUtil.getUser(request);
        String userId = userDto.getId().toString();

        SnowflakeIdGenerator sfg = new SnowflakeIdGenerator();
        long financeOrderId = sfg.nextId();

        Map<Object, Object> entries = redisTemplate.opsForHash().entries("CART:1");
        ArrayList<FinanceOrderDetail> financeOrderDetails = new ArrayList<>();
        for (Map.Entry<Object, Object> entry : entries.entrySet()) {
            //System.out.println(entry.getKey()+":"+entry.getValue());
            SkuDto skuDto1 = JSONObject.parseObject(entry.getValue().toString(), SkuDto.class);
            skuDto1.setId(Long.parseLong(entry.getKey().toString()));
            FinanceOrderDetail financeOrderDetail = new FinanceOrderDetail();
            financeOrderDetail.setFinanceSkuId(skuDto1.getId());
            financeOrderDetail.setFinanceNum(skuDto1.getCount());
            financeOrderDetail.setFinancePrice(BigDecimal.valueOf(skuDto1.getFinanceSkuPrice()));;
            financeOrderDetail.setFinanceOrderId(financeOrderId);
            financeOrderDetail.setCreateBy(userId);
            financeOrderDetails.add(financeOrderDetail);
        }

            return financeOrderDetails;
    }
}




